<template>
  <!-- 分配角色对话框 -->
  <el-dialog title="分配角色" :visible.sync="rolesDialogVisible" width="40%" @close="setRoleDiaClose">
    <div>
      <p>当前的用户：{{changeuserinfo.username}}</p>
      <p>当前的角色：{{changeuserinfo.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="rolesDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addRoles">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean
    },
    changeuserinfo: {
      type: Object
    }
  },
  data() {
    return {
      rolesDialogVisible: false,
      selectedRoleId: '',
      userInfo: {},
      rolesList: {}
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 下拉重置
    setRoleDiaClose() {
      this.userInfo = {}
      this.selectedRoleId = ''
    },
    // 分配角色
    async addRoles() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.changeuserinfo.id}/role`,
        { rid: this.selectedRoleId }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.$emit('changeSuccess')
      // this.getUserList()
      this.rolesDialogVisible = false
    }
  },
  watch: {
    visible: function(val) {
      this.rolesDialogVisible = val
    },
    rolesDialogVisible: function(val) {
      this.$emit('update:visible', val)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
